package cn.kai.basic.service.impl;

import cn.kai.basic.anno.PreAuthorize;
import cn.kai.basic.emun.RequireTypeEum;
import cn.kai.basic.service.IPermissionScanService;
import cn.kai.basic.util.SpringUtil;
import cn.kai.system.domain.Permission;
import cn.kai.system.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class PermissionScanServiceImpl implements IPermissionScanService {

    @Autowired
    private PermissionMapper permissionMapper; // 权限表映射器

    /**
     * 方式一
     */
    @Override
    public void scanPermission() {
        //获取context，这个context中有所有被Spring管理的对象
        ApplicationContext context = SpringUtil.getContext();
        //获取所有的controller类
        Map<String, Object> allController = this.getAllController(context);
        //遍历key的名称和value的对象
        allController.forEach((k,v)->{
            Class<?> aClass = v.getClass();
            /**
             * 如果 当前类不包含PreAuthorize注解 那么直接下次遍历 这种情况需要在controller类上也标记PreAuthorize注解
             * 如果不想在类上打注解 那么就不需要这个判断
             */
            if (!aClass.isAnnotationPresent(PreAuthorize.class)){
                return;
            }
            // 如果是动态代理类 那么它的方法也是动态代理方法，那么我们就不能直接使用getAnnotation获取到
            // 方法上的自定义注解在这里判断是否是代理类 是的话 通过获取父类的class获取到类的正常class文件
            if (Proxy.isProxyClass(aClass) || aClass.getName().contains("EnhancerBySpringCGLIB") ||
            aClass.getName().contains("$$")){
                aClass = aClass.getSuperclass();
            }
            //获取到当前类的所有对象
            Method[] methods = aClass.getMethods();
            // 遍历方法获取到所有带有 PreAuthorize注解的方法
            List<Method> allMethods = Arrays.stream(methods).filter(me -> null != me.getAnnotation(PreAuthorize.class)).collect(Collectors.toList());

            // =====================下面写我们自己的业务代码=====================
            //获取类的请求路径
            String baseUrl = this.getClassPath(aClass);
            allMethods.forEach(method -> {
                //获取方法上的请求路径
                String methodRequestMapping = this.getMethodRequestMapping(method);
                String allUrl = baseUrl + methodRequestMapping;
                //获取方法上的注解值
                PreAuthorize annotation = method.getAnnotation(PreAuthorize.class);
                String name = annotation.name();
                String sn = annotation.sn();
                Permission permission = initPermission(name, sn, allUrl);
                Permission tmpPermission = permissionMapper.findBySn(sn);
                if (null == tmpPermission){
                    permissionMapper.add(permission);
                }else {
                    permission.setId(tmpPermission.getId());
                    permissionMapper.update(permission);
                }
            });
        });
    }

    /**
     * 获取所有的controller类
     * @param context
     * @return
     */
    private Map<String,Object> getAllController(ApplicationContext context){
        //key为类名，value为类的对象
        Map<String, Object> allControllerMap = context.getBeansWithAnnotation(RestController.class);//获取对象和注解
        //获取Controller标记的类
        allControllerMap.putAll(context.getBeansWithAnnotation(Controller.class));
        // todo 如果controller还需要别的注解需要扫描的话，再添加即可
        return allControllerMap;
    }

    /**
     * 获取类的请求路径
     * @param aClass
     * @return
     */
    private String getClassPath(Class<?> aClass){
        RequestMapping classRequestMapping = aClass.getAnnotation(RequestMapping.class);
        String[] classValue = classRequestMapping.value();
        if (null == classValue || classValue.length<=0){
            return "";
        }
        StringBuffer sb = new StringBuffer();
        Arrays.stream(classValue).forEach(sb::append);
        return sb.toString();
    }

    /**
     * 获取方法上的请求路径
     * @param method
     * @return
     */
    private String getMethodRequestMapping(Method method){
        Annotation[] annotations = method.getAnnotations();
        Optional<Annotation> first = Arrays.stream(annotations)
                .filter(anno -> RequireTypeEum.lsit().contains(anno.annotationType().getSimpleName()))
                .findFirst();
        if (!first.isPresent()){
            return "";
        }
        Annotation annotation = first.get();
        InvocationHandler invo = Proxy.getInvocationHandler(annotation);
        Map<String,String[]> map = (Map<String, String[]>) getFieldValue(invo, "memberValues");
        if (CollectionUtils.isEmpty(map) || null == map.get("value") || 0 >= map.get("value").length){
            return "";
        }
        return map.get("value")[0];
    }

    /**
     * 获取字段的值
     * @param object
     * @param property
     * @param <T>
     * @return
     */
    public static <T> Object getFieldValue(T object,String property){
        if (object != null && property != null){
            Class<T> currClass = (Class<T>) object.getClass();
            try {
                Field field = currClass.getDeclaredField(property);
                field.setAccessible(true);
                return field.get(object);
            }catch (NoSuchFieldException e){
                throw new IllegalArgumentException(currClass + "has no property:" + property);
            }catch (IllegalArgumentException e){
                throw e;
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }

    private Permission initPermission(String name,String sn,String url){
        Permission permission = new Permission();
        permission.setName(name);
        permission.setSn(sn);
        permission.setUrl(url);
        return permission;
    }

}
